package com.nd.mobile.study.common.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Environment;

import com.nd.mobile.study.common.config.Config;
import com.nd.mobile.study.common.constants.Tips;
import com.nd.mobile.study.common.exception.LocalErrorException;

public class FileUtils {

	public static final String	TAG	= "FileUtils";

	public static String		cacheDir;
	public static String		sendDir;
	public static String		databaseDir;
	public static String		saveDir;
	public static String		tmpDir;

	static {
		// 得到当前缓存的目录
		String pattern = new StringBuilder().append(Environment.getDataDirectory()).append(File.separator).append("data")
				.append(File.separator).append(Config.PACKAGE).append(File.separator).append("%s").append(File.separator).toString();

		cacheDir = String.format(pattern, "cache");
		saveDir = String.format(pattern, "save");
		sendDir = String.format(pattern, "send");
		databaseDir = String.format(pattern, "databases");
		tmpDir = Environment.getExternalStorageDirectory() + File.separator + Config.SD_STORAGE + File.separator + "tmp" + File.separator;
	}

	public static String getTmpDirPath() {
		return "file:///mnt/sdcard/" + "/" + Config.SD_STORAGE + "/tmp/";
	}

	/**
	 * 
	 * 作用:获取目录的File，如果目录不存在，则创建 参数:
	 * 
	 * @param dirName
	 * @return File
	 */
	public static File getDir(String dirName) {
		File dir = new File(dirName);
		if (dir.exists() == false) {
			dir.mkdirs();
		}
		return dir;
	}

	/**
	 * 作用:删除文件 参数:
	 * 
	 * @param dir
	 * @param fileName
	 */
	public static void delete(String dir, String fileName) {
		File file = new File(dir + fileName);
		if (file.exists()) {
			file.delete();
		}
	}

	/**
	 * 创建文件
	 * 
	 * @param dirName
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public static File create(String dirName, String fileName) throws IOException {
		File file = new File(dirName + fileName);
		if (!file.exists()) {
			file.createNewFile();
		}
		return file;
	}

	/**
	 * 
	 * 作用:判断文件是否存在
	 * 
	 * @param dirName
	 * 
	 * @param fileName
	 * @return
	 */
	public static boolean isFileExist(String dirName, String fileName) {
		File file = new File(dirName + fileName);
		return file.exists();
	}

	/**
	 * 
	 * 作用:判断文件是否存在
	 * 
	 * @param fileName
	 * @return
	 */
	public static boolean isFileExist(String fileName) {
		File file = new File(fileName);
		return file.exists();
	}

	/**
	 * 
	 * 作用:获取文件上次修改时间 参数:
	 * 
	 * @param dirName
	 * 
	 * @param fileName
	 * @return
	 */
	public static long getFileLastModifiiedTime(String dirName, String fileName) {
		File file = new File(dirName + fileName);
		return file.lastModified();
	}

	/**
	 * 
	 * 作用:检查缓存文件是否超过了默认的缓存过期时间 参数:
	 * 
	 * @param dirName
	 * 
	 * @param fileName
	 * @return 超期返回true
	 */
	public static boolean isFileExpired(String dirName, String fileName) {
		File file = new File(dirName + fileName);
		return (System.currentTimeMillis() - file.lastModified()) > Config.DEFAULT_EXPIRE_TIME;
	}

	/**
	 * 功能描述 : 写入文件
	 * <p>
	 * 调用示例:
	 * 
	 * <pre>
	 * </pre>
	 * 参数说明：
	 * <p>
	 * 
	 * @param dirName
	 * @param fileName
	 * @param data
	 * @param isReplace
	 * @return
	 * @throws LocalErrorException
	 *             返回值：
	 *             <p>
	 *             boolean
	 */
	public static boolean writeString(String dirName, String fileName, String data, boolean isReplace) throws LocalErrorException {
		String filePath = dirName + fileName;
		File file = null;
		FileWriter out = null;
		if (!isReplace && isFileExist(dirName, fileName)) {
			return true;
		}
		try {
			getDir(dirName);
			file = create(dirName, fileName);
			out = new FileWriter(filePath);
			out.write(data);
			out.flush();
			file = new File(filePath);
		} catch (IOException e) {
			L.e(TAG, e.getMessage());
			throw new LocalErrorException(Tips.ERROR_ON_FILE_OPER);
		} finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return (null != file && file.exists());
	}

	/**
	 * 功能描述 : 写入文件
	 * <p>
	 * 调用示例:
	 * 
	 * <pre>
	 * </pre>
	 * 参数说明：
	 * <p>
	 * 
	 * @param dirName
	 * @param fileName
	 * @param data
	 * @param isReplace
	 * @return
	 * @throws LocalErrorException
	 *             返回值：
	 *             <p>
	 *             boolean
	 */
	public static boolean writeString(String dirName, String fileName, byte[] data, boolean isReplace) throws LocalErrorException {
		String filePath = dirName + fileName;
		File file = null;
		FileOutputStream out = null;
		if (!isReplace && isFileExist(dirName, fileName)) {
			return true;
		}
		try {
			getDir(dirName);
			file = create(dirName, fileName);
			out = new FileOutputStream(filePath);
			out.write(data);
			file = new File(filePath);
		} catch (IOException e) {
			L.e(TAG, e.getMessage());
			throw new LocalErrorException(Tips.ERROR_ON_FILE_OPER);
		} finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return (null != file && file.exists());
	}

	/**
	 * 功能描述 : 从文件读取
	 * <p>
	 * 调用示例:
	 * 
	 * <pre>
	 * </pre>
	 * 参数说明：
	 * <p>
	 * 
	 * @param dirName
	 * @param fileName
	 * @return
	 * @throws LocalErrorException
	 *             返回值：
	 *             <p>
	 *             String
	 */
	public static String readAsString(String dirName, String fileName) throws LocalErrorException {
		String filePath = dirName + fileName;
		// char[] buf = new char[1024];
		FileReader fileReader = null;
		StringBuffer sb = new StringBuffer();
		BufferedReader reader = null;
		String tmpStr = "";
		try {
			if (!FileUtils.isFileExist(filePath)) new File(filePath);
			reader = new BufferedReader(new FileReader(filePath));
			while ((tmpStr = reader.readLine()) != null) {
				sb.append(tmpStr);
			}
			L.i("----readDataFromFile : ", sb.toString());
			return sb.toString();
		} catch (IOException e) {
			L.e(TAG, e.getMessage());
			throw new LocalErrorException(Tips.ERROR_ON_FILE_OPER);
		} finally {
			if (null != fileReader) {
				try {
					fileReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 删除一个目录下的所有文件
	 * 
	 * @param path
	 */
	public static void cleanDirectory(String path) {
		File file = new File(path);
		if (!file.exists()) {
			return;
		}
		if (!file.isDirectory()) {
			return;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				cleanDirectory(path + File.separator + tempList[i]);
			}
		}
		file.delete();
	}

	/**
	 * 将文件重源地址拷贝到目标地址
	 * 
	 * @param sourePath
	 * @param destPath
	 * @return
	 */
	public static boolean copyFile(String sourePath, String destPath) {
		try {
			InputStream dbFileStream = new FileInputStream(sourePath);
			OutputStream copyFileStream = new FileOutputStream(destPath);
			byte[] buffer = new byte[1024];
			int length;
			while ((length = dbFileStream.read(buffer)) > 0) {
				copyFileStream.write(buffer, 0, length);
			}
			copyFileStream.flush();
			dbFileStream.close();
			copyFileStream.close();
		} catch (Exception e) {
			return false;
		}
		return true;
	}

}
